package msa.ch03.displayable;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.List;

import msa.ch03.MessageArrivalListener;
import msa.ch03.MessageReceiverMidlet;
import msa.ch03.data.MessageDatabase;
import msa.ch03.data.StoredMessage;
import msa.util.View;

public class ListMessages extends List implements MessageArrivalListener {

	private final View view;
	
	private final Command exitCommand;
	private final Command openCommand;
	
	private class MessageReceiverCommandListener implements CommandListener {

		public void commandAction(Command c, Displayable d) {
			if (c == exitCommand) {
				view.show(MessageReceiverMidlet.COMMAND_EXIT);
			} else if (c == openCommand) {
				int index = getSelectedIndex();
				if (index >= 0) {
					StoredMessage message = MessageDatabase.getInstance().get(index);
					view.show(MessageReceiverMidlet.COMMAND_DETAILS, message);
				}
			} else {
				throw new RuntimeException("UNKNOWN COMMAND:" + c);
			}
		}
		
	}
	
	public ListMessages(View view) {
		super("Messages", List.IMPLICIT);
		this.view = view;
		
		exitCommand = new Command("Exit", Command.EXIT, 1);
		openCommand = new Command("Open", Command.OK, 1);
		
		addCommand(exitCommand);
		setSelectCommand(openCommand);
		setCommandListener(new MessageReceiverCommandListener());
		
		StoredMessage messages[] = MessageDatabase.getInstance().list();
		for (int i = 0; i < messages.length; i++) {
			StoredMessage message = messages[i];
			append(message.toString(), null);
		}
		MessageDatabase.getInstance().setMessageArrivalListener(this);
	}

	public void messageArrived(StoredMessage message) {
		append(message.toString(), null);
	}

}
